<template>
  <div class="card-full">
    <div class="search-box">
      <el-form ref="ruleSearchFormRef" class="search-form" :model="searchForm" inline>
        <el-form-item label="" prop="keyword">
          <el-input v-model="searchForm.keyword" placeholder="输入关键词搜索" />
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-select v-model="searchForm.type" placeholder="选择类型">
            <el-option v-for="item in dictTpyeList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-select v-model="searchForm.status" placeholder="选择状态">
            <el-option :key="1" label="正常" :value="1" />
            <el-option :key="2" label="禁用" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button v-permission="'dictionary:list'" class="ml-4" type="primary" @click="getList">查询</el-button>
      <el-button plain @click="(ruleSearchFormRef.resetFields(), getList())">重置</el-button>
    </div>
    <div class="mb-2">
      <el-button v-permission="'dictionary:add'" type="primary" @click="isShow = true">新增</el-button>
    </div>
    <div class="table-box">
      <el-table :data="tableData" style="height: 100%" border>
        <el-table-column prop="type" label="字典类型" min-width="120" align="center" />
        <el-table-column prop="name" label="字典名称" min-width="120" align="center" />
        <el-table-column prop="code" label="字典编码" min-width="120" align="center" />
        <el-table-column prop="desc" label="字典描述" min-width="120" align="center" />
        <el-table-column prop="status" label="字典状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="primary">启用</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120" align="center">
          <template #default="scope">
            <el-button
              v-permission="'dictionary:update'"
              link
              type="primary"
              size="small"
              :disabled="scope.row.is_edit === 2"
              @click="handleClick(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-permission="'dictionary:delete'"
              link
              type="primary"
              size="small"
              :disabled="scope.row.is_edit === 2"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-drawer v-model="isShow" @close="resetForm">
      <template #header>
        <div class="font-bold">{{ form.id ? "编辑" : "新增" }}字典</div>
      </template>
      <template #default>
        <div>
          <el-form ref="ruleFormRef" label-position="right" label-width="auto" :model="form" :rules="rules">
            <el-form-item label="字典名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入字典名称" />
            </el-form-item>
            <el-form-item label="字典编码" prop="code" placeholder="请输入字典编码">
              <el-input v-model="form.code" />
            </el-form-item>
            <el-form-item label="字典类型" prop="type" placeholder="请输入字典类型">
              <el-select
                v-model="form.type"
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                placeholder="请输入或者选择字典类型"
              >
                <el-option v-for="item in dictTpyeList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="字典描述" prop="desc">
              <el-input v-model="form.desc" type="textarea" placeholder="请输入字典描述" />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="confirmClick(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ElForm, ElMessage } from "element-plus";
import * as Api from "@/api/modules/dict";
import type { FormInstance, FormRules } from "element-plus";

const ruleSearchFormRef = ref<FormInstance>();
const searchForm = ref({
  keyword: "",
  type: null,
  status: null
});
const tableData = ref([]);
const getList = () => {
  Api.getDictList({
    ...searchForm.value,
    page: currentPage.value,
    page_size: pageSize.value
  }).then(res => {
    tableData.value = res.data.list;
    total.value = res.data.total;
  });
};
const dictTpyeList = ref<string[]>([]);
const getDictAll = async () => {
  const { data } = await Api.getDictType();
  dictTpyeList.value = data;
};

const isShow = ref(false);
const form = ref<Api.Dict>({
  type: "",
  status: 1
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<Api.Dict>>({
  name: { required: true, message: "请输入字典名称", trigger: "blur" },
  code: { required: true, message: "请输入字典编码", trigger: "blur" },
  type: { required: true, message: "请输入或选择字典类型", trigger: "blur" }
});

const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (form.value.id) {
        await Api.editDict(form.value).then(res => {
          getList();
          isShow.value = false;
        });
      } else {
        await Api.addDict(form.value).then(res => {
          getList();
          isShow.value = false;
        });
      }
      ElMessage({
        message: form.value.id ? "编辑成功" : "添加成功",
        type: "success"
      });
      resetForm();
    }
  });
};
const handleClick = async row => {
  form.value = row;
  isShow.value = true;
};
const handleDelete = (id: number) => {
  Api.delDict({ ids: [id] })
    .then(res => {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      isShow.value = false;
    })
    .catch(err => {
      ElMessage({
        message: err.message,
        type: "success"
      });
    });
};
const resetForm = () => {
  form.value = {
    type: "",
    status: 1
  };
  isShow.value = false;
};

const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

onMounted(() => {
  getList();
  getDictAll();
});
</script>
<style lang="scss" scoped>
:deep(.el-drawer__footer) {
  padding: 15px;
  border-top: 1px solid var(--color-border-2);
}
:deep(.el-drawer__header) {
  margin-bottom: 0;
}
</style>
